package com.bwie.auth.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bwie.auth.feign.SystemFeign;
import com.bwie.auth.service.AuthServie;
import com.bwie.common.constants.JwtConstants;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.User;
import com.bwie.common.domain.response.Jwtresponse;
import com.bwie.common.result.Result;
import com.bwie.common.utils.JwtUtils;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class AuthServiceimpl implements AuthServie {
    @Autowired
    private SystemFeign systemFeign;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private HttpServletRequest request;

    @Override
    public Result<Jwtresponse> login(User user) {
        Result<User> byName = systemFeign.findByName(user.getUserName());
        User data = byName.getData();
        if(data.getUserName()==null){
            return Result.error("账号为空");
        }

        if(!user.getUserPwd().equals(data.getUserPwd())){
            return Result.error("密码错误");
        }

        String userKey = UUID.randomUUID().toString().replaceAll("-", "");

        HashMap<String, Object> map = new HashMap<>();

        map.put(JwtConstants.USER_KEY, userKey);

        String token = JwtUtils.createToken(map);

        redisTemplate.opsForValue().set(TokenConstants.LOGIN_TOKEN_KEY+userKey,
                JSON.toJSONString(data),25, TimeUnit.MINUTES);

        Jwtresponse jwtresponse = new Jwtresponse();

        jwtresponse.setToken(token);

        jwtresponse.setPriceTime("25MIN");

        return Result.success(jwtresponse);

    }

    @Override
    public User info() {
        String header = request.getHeader(TokenConstants.TOKEN);

        String userKey = JwtUtils.getUserKey(header);

        String s = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);

        User user = JSONObject.parseObject(s, User.class);

        return user;
    }
}
